package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public Order add(Order order) {

        OrderSetting orderSetting = orderSettingDao.selectByDate(order.getOrderDate());

        if (orderSetting == null) {
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        } else if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }
        long count = orderDao.countByMemberAndDateAndSetmeal(order.getMemberId(),order.getOrderDate(),order.getSetmealId());
        if (count > 0) {
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        orderDao.insert(order);

        orderSettingDao.updateReservationsById(orderSetting.getId(),orderSetting.getReservations() + 1);

        return orderDao.selectById(order.getId());
    }
//    @Override
//    public Order findById(Integer id) {
//        return orderDao.selectById(id);
//    }

    @Override
    public Map findById(Integer id) {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",new SimpleDateFormat("yyyy-MM-dd").format(orderDate));
        }
        return map;
    }
}
